<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>机器商品管理</title>
    <link rel="stylesheet" href="/static/lib/layui-v2.5.6/layui-v2.5.6/layui/css/layui.css">
    <style>
        .layui-table-cell{
            height:60px !important;
            line-height: 60px!important;
        }
        .layui-table-cell{
            height:38px;
            line-height: 38px;
        }
        .layui-col-xs1{
            height: 66px;
            line-height: 66px;
            margin: 5px 5px 0 0;
            text-align: center;
            font-size: 20px;
            cursor: pointer;
        }
        .info{
            font-size: 14px;
            color: rgb(110, 108, 108);
            line-height: 36px;
        }
        .layui-icon-search{
            font-size: 30px;
            color: #009688;
            cursor: pointer;
            margin-left: 40px;
        }
        .layui-icon{
            cursor: pointer;
        }

        .btn-box {
            position: relative;
        }

        .file-ipt {
            position: absolute;
            left: 0;
            top: 0;
            opacity: 0; 
        }

        .btn {
            width: 100px;
            height: 30px;
            background-color: white;
            color: #009688;
            margin-right: 80px;
            border: none;
            border-radius: 10px;
        }
        input[type="checkbox"]{width:20px;height:20px;display: inline-block;text-align: center;vertical-align: middle; line-height: 18px;position: relative;}
        input[type="checkbox"]::before{content: "";position: absolute;top: 0;left: 0;background: #fff;width: 100%;height: 100%;border: 1px solid #d9d9d9}
        input[type="checkbox"]:checked::before{content: "\2713";background-color: #fff;position: absolute;top: 0;left: 0;width:100%;border: 1px solid #e50232;color:#e50232;font-size: 20px;font-weight: bold;}    
    </style>
</head>
<body>
    <table id="demo" lay-filter="test"></table>




<!-- //TODO:商品增加和修改 -->
<div id="itemUpdate" style="display: none;margin-top: 30px;">
    <form class="layui-form">
        
        <div class="layui-form-item">
            <label class="layui-form-label">商品分类</label>
            <div class="layui-input-inline">
                <select name="itemCategory_2" lay-verify="" id="itemCategory" class="itemCategory">
                    <option value="">商品分类</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品名称</label>
            <div class="layui-input-inline">
                <input id="itemName" type="text" name="itemName" required lay-verify="required" placeholder="请输入商品名称" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品价格</label>
            <div class="layui-input-inline">
                <input id="itemPrice" type="text" name="itemPrice" required lay-verify="required" placeholder="请输入商品价格" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">商品规格</label>
            <div class="layui-input-inline">
                <input id="itemSpecifications" type="text" name="itemSpecifications" required lay-verify="required" placeholder="请输入商品规格" class="layui-input">
            </div>
        </div>
        <form class="layui-form">
            <div class="layui-form-item btn-box" style="margin: 30px 0 0 30px;">
                <button class="btn" style="background-color: #ccc;">点击上传图片</button>
                <input type="file" id="imgAdd" class="file-ipt">
            </div>
        </form>
    </form>
</div>


    <script type="text/html" id="barDemo">
        <i class="layui-icon layui-icon-edit" lay-event="itemUpdate_1" title="信息修改"></i>
        <i class="layui-icon layui-icon-delete" lay-event="itemDel_1" title="商品删除"></i>
        <i class="layui-icon layui-icon-upload-circle" lay-event="itemStatus_1" title="商品状态改变"></i>
    </script>

    <script type="text/html" id="toolbarDemo">
        
        <div class="layui-inline" style="width: 150px;">
            <select name="itemCategory_2" lay-verify="" id="itemCategory_2" class="itemCategory">
                <option value="">商品分类</option>
            </select>
        </div>
        <div class="layui-inline" style="width: 150px;">
            <select name="itemStatus_2" lay-verify="" id="itemStatus_2">
                <option value="">商品状态</option>
                <option value="0">未上架</option>
                <option value="1">正常</option>
            </select>
        </div>
        <div class="layui-inline">
            <div class="layui-input-inline" style="width: 150px;">
              <input type="text" name="itemName_2" id="itemName_2" placeholder="输入商品名" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-inline">
            <i class="layui-icon layui-icon-search" lay-event="itemlistSearch_2" title="搜索刷新"></i>
        </div>
        <div class="layui-form-item">
            <button class="layui-btn layui-btn-sm layui-btn-radius" lay-event="itemAdd" style="margin-top:8px">添加商品</button>
        </div>
    </script>


    
    <script src="/static/lib/layui-v2.5.6/layui-v2.5.6/layui/layui.js"></script>
    <script>
        
        
        
        

        layui.use(['table','laydate','form','util','form'], function(){
            var $ = layui.jquery;
            var table = layui.table;
            var laydate =layui.laydate;
            var form = layui.form;
            var util = layui.util;

            getCategory()
            table.render({
                elem: '#demo',
                height: 'full-15',
                //TODO:
                url: '/admin/item/queryItem', //数据接口
                page: {layout: ['prev', 'page', 'next', 'skip', 'count']}, //开启分页
                toolbar: '#toolbarDemo',
                defaultToolbar: [],
                limit: 6,
                id: 'adTest',
                cols: [[ //表头
                {field: 'id', title: '商品ID', width:'10%', sort: true, fixed: 'left'},
                {field: 'item_name', title: '商品名称', width:'22%',},
                {field: 'picture_url', title: '商品图片', width:'15%',  templet:'<div><img style="height:60px" src="https://vm.fowotek.com{{d.picture_url}}" </div>'},
                {field: 'categoryName', title: '商品类别', templet:"<div>{{ d.category.categoryName }}</div>", width:'13%'},
                {field: 'price', title: '商品价格', templet:'<div>{{d.price}}元</div>', width:'10%'} ,
                {field: 'specifications', title: '商品规格',  width: '10%'},
                {field: 'item_status', title: '商品状态', width: '10%', templet:'<div>{{goodsStatus(d.item_status)}}</div>'},
                {fixed: 'right', width:'10%', title: '操作', align:'center', toolbar: '#barDemo'}
                ]],


                parseData: function(res){ //res 即为原始返回的数据
                    return {
                    "code": res.success, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                    };
                },
                request: {
                    pageName: 'pageNum', //页码的参数名称，默认：page
                    limitName: 'pageSize' //每页数据量的参数名，默认：limit
                },
                response: {
                    // statusName: 'success', //规定数据状态的字段名称，默认：code
                    statusCode: true //规定成功的状态码，默认：0
                }
            });
        
            table.on('toolbar(test)', function(obj){
                sessionStorage.setItem("itemCategory_2_1", $("#itemCategory_2").val());
                sessionStorage.setItem("itemStatus_2_1", $("#itemStatus_2").val());
                sessionStorage.setItem("itemName_2_1", $("#itemName_2").val());
                //TODO:搜索栏的实现
                switch(obj.event){
                    case 'itemlistSearch_2':
                    var item_category_id = $("#itemCategory_2").val()
                    var item_status = $("#itemStatus_2").val()
                    var item_name = $("#itemName_2").val()
                    
                    getCategory(item_category_id)
                    table.reload('adTest', {
                        where: { //设定异步数据接口的额外参数，任意设
                            item_category_id: $("#itemCategory_2").val() || undefined,
                            item_status: $("#itemStatus_2").val() || undefined,
                            item_name: $("#itemName_2").val() || undefined
                        },
                        done: function(res, curr, count){
                            this.where={};
                        },
                        page: {
                            curr: 1 //重新从第 1 页开始
                        },
                    });

                    if (sessionStorage.getItem("itemStatus_2_1") == '') {
                        $("#itemStatus_2").attr('text','商品状态')
                    }else if(sessionStorage.getItem("itemStatus_2_1") == '0'){
                        $("#itemStatus_2 option[value= '0']").attr("selected", true);
                    }else if (sessionStorage.getItem("itemStatus_2_1") == '1') {
                        $("#itemStatus_2 option[value= '1']").attr("selected", true);
                    }

                    if (sessionStorage.getItem("itemName_2_1") == '') {
                        $("#itemName_2").attr('placeholder','输入商品名')
                    }else{
                        $("#itemName_2").attr('placeholder',sessionStorage.getItem("itemName_2_1"))
                    }
                    
                    break;
                    case 'itemAdd':
                    $("#itemName").val('')
                    $("#itemPrice").val('')
                    $("#itemSpecifications").val('')
                    form.render('select'); //更新全部
                    layer.open({
                        type: 1,
                        // skin: 'layui-layer-rim', //加上边框
                        area: ['400px', '540px'], //宽高
                        title: '商品信息添加',
                        btn: ['添加','取消'],
                        content: $('#itemUpdate'),
                        yes: function(index){
                            var file = $("#imgAdd")[0].files[0];//获取文件
                            var formData = new FormData();
                            if ($("#itemCategory").val() == '' || $("#itemName").val() == '' || $("#itemPrice").val() == '' || $("#itemSpecifications").val() == '') {
                                layer.msg('商品信息不能为空')
                            } else {
                                if (file == undefined) {
                                    formData.append("item_category_id", $("#itemCategory").val());
                                    formData.append("item_name", $("#itemName").val());
                                    formData.append("price", $("#itemPrice").val());
                                    formData.append("specifications", $("#itemSpecifications").val());
                                }else {
                                    formData.append("picture", file);
                                    formData.append("item_category_id", $("#itemCategory").val());
                                    formData.append("item_name", $("#itemName").val());
                                    formData.append("price", $("#itemPrice").val());
                                    formData.append("specifications", $("#itemSpecifications").val());
                                }
                                $.ajax({
                                    type: "post",
                                //TODO:
                                    url: "/admin/item/addItem",
                                    data: formData,
                                    dataType: "json",
                                    processData: false,
                                    contentType: false,
                                    success: function(mag){
                                        layer.msg(mag.message)
                                        table.reload('adTest')
                                        getCategory(item_category_id)
                                    }
                                })
                                layer.close(index);
                                getCategory(item_category_id)
                                form.render('select');
                            }
                            
                        }
                    })
                    break;
                };
            });

            table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
                var data = obj.data; //获得当前行数据
                var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                var tr = obj.tr; //获得当前行 tr 的 DOM 对象（如果有的话）
                if(layEvent === 'itemUpdate_1'){
                    form.render('select'); //更新全部
                    $("#itemSpecifications").val('')
                    $("#itemName").val('')
                    $("#itemPrice").val('')
                    $("#imgPath").val('')
                    
                    layer.open({
                        type: 1,
                        skin: 'layui-layer-rim', //加上边框
                        area: ['400px', '540px'], //宽高
                        title: '商品信息修改',
                        btn: ['修改','关闭'],
                        content: $('#itemUpdate'),
                        yes: function(index){
                            var file = $("#imgAdd")[0].files[0];//获取文件
                            var formData = new FormData();

                            console.log(data.id)
                            formData.append("item_id", data.id);
                            if (file != undefined) {
                                formData.append("picture", file);
                            }
                            if ($("#itemCategory").val() != '') {
                                formData.append("item_category_id", $("#itemCategory").val());
                            }
                            if ($("#itemName").val() != '') {
                                formData.append("item_name", $("#itemName").val());
                            }
                            if ($("#itemPrice").val() != '') {
                                formData.append("price", $("#itemPrice").val());
                            }
                            if ($("#itemSpecifications").val() != '') {
                                formData.append("specifications", $("#itemSpecifications").val());
                            }

                            $.ajax({
                                type: "post",
                            //TODO:
                                url: "/admin/item/updateItem",
                                data: formData,
                                dataType: "json",
                                processData: false,
                                contentType: false,
                                success: function(mag){
                                    layer.msg(mag.message)
                                    table.reload('adTest')
                                    layer.close(index);
                                    getCategory()
                                },
                                error: function(){
                                    layer.msg('修改商品信息失败')
                                    table.reload('adTest');
                                    layer.close(index);
                                    getCategory()
                                }
                            })
                        }
                    });

                   

                    
// TODO:下面测试合格
                } else if(layEvent === 'itemDel_1'){ //删除
                    console.log(data)
                    if (data.item_status == 1) {
                        layer.msg('上架商品无法删除')
                    }else{
                        layer.confirm('真的删除行么', function(index){
                            $.ajax({
                                type: "post",
                    //TODO:
                                url: "/admin/item/deleteItem",
                                data: {item_id: data.id},
                                dataType: "json",
                                async: false,
                                success: function(mag){
                                    layer.msg(mag.message)
                                }
                            })
                            table.reload('adTest')
                            layer.close(index);
                            form.render('select');
                        });
                    }
                    
                } else if(layEvent === 'itemStatus_1'){ //编辑
                    if (data.item_status == 0) {
                        layer.confirm('上架商品', function(index){
                            $.ajax({
                                type: "post",
                //TODO:
                                url: "/admin/item/onTheMarket",
                                data: {item_id: data.id},
                                dataType: "json",
                                success: function(mag){
                                    layer.msg(mag.message)
                                    if (mag.success == true) {
                                        obj.update({
                                            item_status: '1'
                                        });
                                        layer.close(index);
                                    }
                                }
                            })
                            
                        });
                    }else {
                        layer.confirm('下架商品', function(index){
                            $.ajax({
                                type: "post",
                //TODO:
                                url: "/admin/item/offTheShelf",
                                data: {item_id: data.id},
                                dataType: "json",
                                success: function(mag){
                                    layer.msg(mag.message)
                                    if (mag.success == true) {
                                        obj.update({
                                            item_status: '0'
                                        });
                                        layer.close(index);
                                    }
                                }
                            })
                            
                        });
                    }
                    
                }
            });
        
        



            function getCategory(num) {
                $.ajax({
                    type: "get",
                //TODO:
                    url: "/admin/itemCategory",
                    data: '',
                    dataType: "json",
                    success: function(mag){
                        var tag = '<option value="">商品分类</option>'
                        for (let i = 0; i < mag.length; i++) {
                            if (mag[i].id == num) {
                                var tag1 = '<option selected="selected" value="'+ mag[i].id +'">'+ mag[i].categoryName +'</option>'
                            }else{
                                var tag1 = '<option value="'+ mag[i].id +'">'+ mag[i].categoryName +'</option>'
                            }
                            tag += tag1
                        }
                        $(".itemCategory").html(tag)
                    }
                })
            }


        });
        function dateTime(date) {
            if (date != '') {
                var dateTime = new Date(date).getTime()
            }else{
                var dateTime = ''
            }
            return dateTime
        }
        function goodsStatus(num) {
            if (num == 0) {
                var status = '<span style="color: #f173e1;">未上架</span>'
            }else {
                var status = '正常'
            }
            return status
        }
        
    </script>
</body>
</html>